/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.sys.multishop.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import javax.validation.Valid;

import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.sys.comment.constant.MenuType;
import com.yami.shop.sys.comment.model.ShopMenu;
import com.yami.shop.sys.comment.service.ShopMenuService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.common.util.PageParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 菜单管理
 *
 * @author yami
 * @date 2021-03-01 17:42:09
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys/shopMenu")
public class ShopMenuController {

    private final ShopMenuService shopMenuService;

    /**
     * 分页查询
     *
     * @param page     分页对象
     * @param shopMenu 菜单管理
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<ShopMenu>> getShopMenuPage(PageParam<ShopMenu> page, ShopMenu shopMenu) {
        return ResponseEntity.ok(shopMenuService.page(page, new LambdaQueryWrapper<ShopMenu>()));
    }

    @GetMapping("/nav")
    @ApiOperation(value="获取用户所拥有的菜单和权限", notes="通过登陆用户的userId获取用户所拥有的菜单和权限")
    public ResponseEntity<Map<Object, Object>> nav(){
        List<ShopMenu> shopMenus = shopMenuService.listMenuByEmployeeId(SecurityUtils.getShopUser().getEmployeeId());
        Collection<GrantedAuthority> authorities = SecurityUtils.getShopUser().getAuthorities();

        return ResponseEntity.ok(MapUtil.builder().put("menuList", shopMenus).put("authorities", authorities).build());
    }

    /**
     * 获取菜单页面的表
     *
     * @return
     */
    @GetMapping("/table")
    public ResponseEntity<List<ShopMenu>> table() {
        List<ShopMenu> shopMenus = shopMenuService.listMenuAndBtn();
        return ResponseEntity.ok(shopMenus);
    }

    /**
     * 所有菜单列表(用于新建、修改角色时 获取菜单的信息)
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取用户所拥有的菜单(不包括按钮)", notes = "通过登陆用户的userId获取用户所拥有的菜单和权限")
    public ResponseEntity<List<ShopMenu>> list() {
        List<ShopMenu> shopMenus = shopMenuService.listSimpleMenuNoButton();
        return ResponseEntity.ok(shopMenus);
    }

    /**
     * 选择菜单
     */
    @GetMapping("/listRootMenu")
    public ResponseEntity<List<ShopMenu>> listRootMenu() {
        //查询列表数据
        List<ShopMenu> shopMenus = shopMenuService.listRootMenu();
        return ResponseEntity.ok(shopMenus);
    }

    /**
     * 选择子菜单
     */
    @GetMapping("/listChildrenMenu")
    public ResponseEntity<List<ShopMenu>> listChildrenMenu(Long parentId) {
        //查询列表数据
        List<ShopMenu> shopMenus = shopMenuService.listChildrenMenuByParentId(parentId);
        return ResponseEntity.ok(shopMenus);
    }

    /**
     * 通过id查询菜单管理
     *
     * @param menuId id
     * @return 单个数据
     */
    @GetMapping("/info/{menuId}")
    public ResponseEntity<ShopMenu> getById(@PathVariable("menuId") Long menuId) {
        return ResponseEntity.ok(shopMenuService.getById(menuId));
    }

    /**
     * 新增菜单管理
     *
     * @param shopMenu 菜单管理
     * @return 是否新增成功
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys:shopMenu:save')")
    public ResponseEntity<Boolean> save(@RequestBody @Valid ShopMenu shopMenu) {
        //数据校验
        verifyForm(shopMenu);
        return ResponseEntity.ok(shopMenuService.save(shopMenu));
    }

    /**
     * 修改菜单管理
     *
     * @param shopMenu 菜单管理
     * @return 是否修改成功
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys:shopMenu:update')")
    public ResponseEntity<String> updateById(@RequestBody @Valid ShopMenu shopMenu) {
        //数据校验
        verifyForm(shopMenu);
        if (shopMenu.getType() == MenuType.MENU.getValue() && StrUtil.isBlank(shopMenu.getUrl())) {
            // 菜单URL不能为空
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.menu.exist"));
        }
        boolean isOk = shopMenuService.updateById(shopMenu);
        return ResponseEntity.ok(String.valueOf(isOk));
    }

    /**
     * 通过id删除菜单管理
     *
     * @param menuId id
     * @return 是否删除成功
     */
    @DeleteMapping("/{menuId}")
    @PreAuthorize("@pms.hasPermission('sys:shopMenu:delete')")
    public ResponseEntity<String> removeById(@PathVariable Long menuId) {
        if(menuId <= Constant.SYS_MENU_MAX_ID){
            // 系统菜单，不能删除
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.menu.delete.error"));
        }
        //判断是否有子菜单或按钮
        List<ShopMenu> shopMenus = shopMenuService.listChildrenMenuByParentId(menuId);
        if(shopMenus.size() > 0){
            // 请先删除子菜单或按钮
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.sys.menu.child.delete"));
        }

        shopMenuService.deleteMenuAndRoleMenu(menuId);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(ShopMenu shopMenu) {

        if (Objects.equals(shopMenu.getMenuId(), shopMenu.getParentId())) {
            // 自己不能是自己的上级
            throw new YamiShopBindException("yami.sys.menu.user.error");
        }
        if (shopMenu.getType() == MenuType.MENU.getValue()) {
            if (StrUtil.isBlank(shopMenu.getUrl())) {
                // 菜单URL不能为空
                throw new YamiShopBindException("yami.sys.menu.exist");
            }
        }

        //上级菜单类型
        int parentType = MenuType.CATALOG.getValue();
        if (shopMenu.getParentId() != 0) {
            ShopMenu parentMenu = shopMenuService.getById(shopMenu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (shopMenu.getType() == MenuType.CATALOG.getValue() || shopMenu.getType() == MenuType.MENU.getValue()) {
            if (parentType != MenuType.CATALOG.getValue()) {
                // 上级菜单只能为目录类型
                throw new YamiShopBindException("yami.sys.menu.superior.list");
            }
            return;
        }

        //按钮
        if (shopMenu.getType() == MenuType.BUTTON.getValue()) {
            if (parentType != MenuType.MENU.getValue()) {
                // 上级菜单只能为菜单类型
                throw new YamiShopBindException("yami.sys.menu.superior.menu");
            }
        }
    }
}
